package br.com.portalaberto.connection.chain;

import java.io.*;
import java.util.*;
import javax.microedition.io.*;
import javax.microedition.io.file.FileConnection;
import javax.microedition.lcdui.Form;
import javax.microedition.location.Coordinates;
import javax.microedition.location.Criteria;
import javax.microedition.location.Location;
import javax.microedition.location.LocationException;
import javax.microedition.location.LocationProvider;

import br.com.portalaberto.core.UIController;

public class HttpClient /*implements Runnable*/{

	private String url;
	//private HttpClient client;
	private String requestMethod;
	private String resultStr;
	public String parametros = null;

	public String getParametros() {
		return parametros;
	}

	public void setParametros(String parametros) {
		this.parametros = parametros;
	}


	private Vector handlers = new Vector (); 
	private int maxIteration = 3; // Max number of challenge/response cycles.


	/*	private String msg;
	private String pathCompleto;
	private double latitude;
	private double longitude;
	private UIController controlador;

	public HttpClient(String pathCompleto, String msg, UIController controlador) {
		this.pathCompleto = pathCompleto;
		this.msg = msg;
		this.controlador = controlador;
	}
	 */	
	public HttpClient() {
	}

	public void setUrl (String url) {
		this.url = url;
	}

	public void setRequestMethod (String method) {
		this.requestMethod = method;
	}

	public void setMaxIteration (int n) {
		maxIteration = n;
	}

	public void addHandler (Handler h) throws Exception {
		handlers.addElement(h);
	}

	public void removeAllHandlers () throws Exception {
		handlers = new Vector ();
	}

	/*public byte [] query (byte [] req) throws Exception {

		boolean needConnect = true;
		HttpConnection c = null;
		InputStream is = null;
		OutputStream os = null;
		ByteArrayOutputStream bos = null;
		byte [] buf = null;

		try {
			int currentIteration = 0;
			while (needConnect) {
				currentIteration++;
				if (currentIteration > maxIteration)
					throw new Exception("Too many Iterations");

				needConnect = false;

				if (c != null) 
					c.close();
				if (os != null)
					os.close();
				System.out.println("iniciando a conexao...");
				c = (HttpConnection) Connector.open (this.url);
				System.out.println("a url eh essa aqui: "+c.getURL());
				System.out.println("conexao iniciada: "+this.requestMethod);
				c.setRequestMethod( this.requestMethod );

				for (int i = 0; i < handlers.size(); i++) {
					((Handler) handlers.elementAt(i)).prepareHeaders(c);
				}
				System.out.println("saiu dos handlers");
				c.setRequestProperty("User-Agent", "Profile/MIDP-1.0, Configuration/CLDC-1.0");
				c.setRequestProperty("Content-Language", "pt-BR");

				if ( req != null ) {
					os = c.openOutputStream ();
					os.write(req);
				}

				for (int i = 0; i < handlers.size(); i++) {
					needConnect = ((Handler) handlers.elementAt(i)).processHeaders(c) || needConnect;
				}
			}
			is = c.openInputStream ();
			bos = new ByteArrayOutputStream();
			buf = new byte[256];
			while (true) {
				int rd = is.read(buf, 0, 256);
				if (rd == -1) break;
				bos.write(buf, 0, rd);
			} 
			buf = bos.toByteArray();
		} finally {
			if (c != null) c.close();
			if (is != null) is.close();
			if (os != null) os.close();
			if (bos != null) bos.close();
		}

		return buf;
	}*/



	public byte [] query (byte [] req) throws Exception {

		boolean needConnect = true;
		HttpConnection c = null;
		InputStream is = null;
		OutputStream os = null;
		ByteArrayOutputStream bos = null;
		byte [] buf = null;

		try {
			int currentIteration = 0;
			while (needConnect) {
				currentIteration++;
				if (currentIteration > maxIteration)
					throw new Exception("Too many Iterations");

				needConnect = false;

				if (c != null) c.close();
				if (os != null) os.close();

				if(requestMethod == HttpConnection.GET){
					c = (HttpConnection) Connector.open (url);
					c.setRequestMethod( requestMethod );

					for (int i = 0; i < handlers.size(); i++) {
						((Handler) handlers.elementAt(i)).prepareHeaders(c);
					}
					c.setRequestProperty("User-Agent",
					"Profile/MIDP-1.0, Configuration/CLDC-1.0");
					c.setRequestProperty("Content-Language", "pt-BR");

					if ( req != null ) {
						os = c.openOutputStream ();
						os.write(req);
					}

					for (int i = 0; i < handlers.size(); i++) {
						needConnect = ((Handler) handlers.elementAt(i)).processHeaders(c) || needConnect;
					}
					is = c.openInputStream ();
					bos = new ByteArrayOutputStream();
					buf = new byte[256];
					while (true) {
						int rd = is.read(buf, 0, 256);
						if (rd == -1) break;
						bos.write(buf, 0, rd);
					} 
					buf = bos.toByteArray();	        	
				}else{
					c = (HttpConnection) Connector.open (url,Connector.READ_WRITE, true);
					c.setRequestMethod( requestMethod );

					for (int i = 0; i < handlers.size(); i++) {
						((Handler) handlers.elementAt(i)).prepareHeaders(c);
					}
					c.setRequestProperty("User-Agent",
					"Profile/MIDP-1.0, Configuration/CLDC-1.0");
					c.setRequestProperty("Content-Language", "pt-BR");

					//Envia os dados para o servidor
					if (parametros != null) {
						os = c.openOutputStream();
						os.write(parametros.getBytes());
						os.close();
						os = null;
						needConnect = false;
					}

				}
			}
		} finally {
			if (c != null) c.close();
			if (is != null) is.close();
			if (os != null) os.close();
			if (bos != null) bos.close();
		}

		return buf;
	}


	/*	public void startConn() {
		Form form = new Form("Session client");

		try {
			this.url = "http://localhost:8080/ServidorPortalAberto/ServidorServlet";

			//client = new HttpClient ();
			byte[] imagemByte = getImageByteArray(pathCompleto);
			String imagemString = new String(imagemByte);
			//elaine- aqui a chamada do metodo de localizacao
			this.getLocation();
			//agora eu passo a latitude e a longitude que eu setei no metodo acima
			Handler h1 = new JSONHandler(msg,imagemString,latitude,longitude);
			//Handler h2 = new BasicAuthHandler("user", "passwd");

			//client.addHandler( h1 );
			//client.addHandler( h2 );
			//client.setUrl( url );
			//client.setRequestMethod( HttpConnection.GET );

			this.addHandler( h1 );
			//this.addHandler( h2 );
			this.setUrl( url );
			this.setRequestMethod( HttpConnection.GET );

			//Worker t = new Worker ();
			//t.setListener(this);
			//t.start();
			System.out.println("iniciando a thread");
			new Thread(this).start();

		} catch (Exception e) {
			e.printStackTrace();
			form.append("Sorry, there is an error fetching");
		}
	}

	public void run () {
		try {
			byte [] result = this.query(null);

			//byte [] result = null;

			//byte [] result = getImageByteArray(pathCompleto);

			if(result != null){
				resultStr = new String(result);
				//resultStr = "OK";
				System.out.println("resultado ok");
			}else{
				resultStr = null;
			}
			controlador.setLiberacao(false);
		} catch (Exception e) {
			e.printStackTrace();
			resultStr = "fetch failed";
		}
	}*/

	public String getResultStr() {
		return resultStr;
	}

	/*	private byte[] getImageByteArray(String caminho){
		InputStream fis = null;
		FileConnection fc = null;
		byte[] imagemBytes = null;
		try	{
			fc = (FileConnection) Connector.open(caminho);
			if (!fc.exists()){
				throw new IOException("File does not exists");
			}
			int data = 0;
			fis = fc.openInputStream();
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			while((data = fis.read())!=-1) {
				baos.write(data);
			}
			imagemBytes = baos.toByteArray();
		}catch (Exception e) {
			e.printStackTrace();
		}finally{
			try {
				fis.close();
				fc.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return imagemBytes;
	}

	private void getLocation(){


		Criteria cr= new Criteria();
		cr.setHorizontalAccuracy(500);


		LocationProvider lp;
		Location l = null;
		Coordinates c = null;



		try {
			lp = LocationProvider.getInstance(cr);
			//timeout de 60 segundos
			l = lp.getLocation(60);
			c = l.getQualifiedCoordinates();
			if(c != null ) {
				  // Use coordinate information
				  latitude = c.getLatitude();
				  longitude = c.getLongitude();
				}

		} catch (LocationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}



	}*/

	/*public byte[] get_Byte_Array(Image img){

		int[] imgRgbData = new int[img.getWidth() * img.getHeight()];
		byte[] imageData = null;
		try{
			img.getRGB( imgRgbData, 0, img.getWidth(), 0, 0, img.getWidth(), img.getHeight() );
		} catch( Exception e ){
		}
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		DataOutputStream dos = new DataOutputStream( baos );

		try{
			for( int i = 0; i < imgRgbData.length; i++ ){
				dos.writeInt( imgRgbData[i] );
			}

			imageData = baos.toByteArray();
			baos.close();
			dos.close();
		}catch(Exception e){

		}
		return imageData;
	}*/
}
